package us.kg.kotoriforest.schedule.service.Impl;

import us.kg.kotoriforest.schedule.dao.SysUserDAO;
import us.kg.kotoriforest.schedule.dao.impl.SysUserDAOImpl;
import us.kg.kotoriforest.schedule.pojo.SysUser;
import us.kg.kotoriforest.schedule.service.SysUserService;
import us.kg.kotoriforest.schedule.util.MD5Util;

/**
 * ClassName: us.kg.kotoriforest.schedule.service.Impl.SysUserServiceImpl </br>
 * Description: {@link SysUserService} 接口的实现类
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/12/3
 */
public class SysUserServiceImpl implements SysUserService {
    private static final SysUserDAO userDAO = new SysUserDAOImpl();

    @Override
    public State register(SysUser sysUser) {
        // 将传入的明文密码加密
        sysUser.setUserPwd(MD5Util.encrypt(sysUser.getUserPwd()));

        // 添加新用户
        int rows = userDAO.insert(sysUser);

        return rows > 0 ? State.QUERY_SUCCESS : State.QUERY_FAIL;
    }

    @Override
    public State login(SysUser sysUser) {
        // 将传入的明文密码加密
        String encrypted = MD5Util.encrypt(sysUser.getUserPwd());

        // 在表中查询用户名对应的用户信息
        SysUser loginUser = userDAO.selectByUsername(sysUser.getUsername());

        if (null == loginUser) {
            return State.USER_NOT_FOUND;
        } else if (!encrypted.equals(loginUser.getUserPwd())) {
            return State.QUERY_FAIL;
        } else {
            sysUser.setUid(loginUser.getUid());
            sysUser.setUserPwd(encrypted);
            return State.QUERY_SUCCESS;
        }
    }

    @Override
    public State checkUsernameUsed(String username) {
        return null == userDAO.selectByUsername(username) ? State.USER_NOT_FOUND : State.USER_ALREADY_EXIST;
    }
}
